<template>
  <div ref="editorElRef" class="editor-el" :style="wrapStyles">
    <div
      v-if="chunk.type === 'img'"
      class="editor-el-img"
      :style="imgWrapStyles"
    >
      <img
        :src="chunk.src"
        draggable="false"
        :style="{
          width: `${chunk.width}px`,
          height: `${chunk.height}px`,
          transform: `matrix(${chunk.transformX}, 0, 0, ${chunk.transformY}, 0, 0)`
        }"
      />
    </div>
    <div
      v-else
      class="editor-el-text"
      :class="{
        'editor-el-text-editing': isShowEditText && index === currentChunkIndex
      }"
      :style="textWrapStyles"
    >
      <span
        :class="{ 'edit-content': isEdit }"
        style="font-weight: inherit"
        :contenteditable="!chunk.priceTag && isEdit"
        v-html="chunk.textContent"
      ></span>
      <span
        v-if="chunk.decimal"
        :style="{
          fontSize: `${chunk.fontSize * 0.7}px`,
          fontWeight: 'inherit'
        }"
      >
        .99
      </span>
    </div>
  </div>
</template>

<script setup name="ImgChunk">
import debounce from 'lodash/debounce'
import { ref, onMounted, onBeforeMount, onBeforeUnmount, getCurrentInstance, computed, watch, nextTick } from 'vue'
import store from '@/store'

const props = defineProps({
  chunk: {
    type: Object,
    default() {
      return {}
    }
  },
  index: {
    type: Number,
    default: 0
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['textChange'])

const that = getCurrentInstance().proxy;
const wrapStyles = ref({})
const imgWrapStyles = ref({
  width: '',
  height: ''
})
const textWrapStyles = ref({
  width: '',
  height: '',
  fontFamily: '',
  fontSize: '',
  fontWeight: '',
  fontStyle: '',
  color: '',
  textAlign: '',
  letterSpacing: '',
  transform: ''
})
const currentEditTextIndex = ref(0)

const size = computed(()=> store.state?.poster?.size)
const scale = computed(() => size.value / 100)
const chunks = computed(()=> store.state?.poster?.chunks)
const currentChunkIndex = computed(()=> store.state?.poster?.currentChunkIndex)
const isShowEditText = computed(()=> store.state?.poster?.isShowEditText)
const editorElRef = ref(null)

watch(props.index, () => {
  wrapStyles.value.index = val + 1
})
watch(props.chunk, (val) => {
  const scale = size.value / 100
  let {
    width,
    height,
    top,
    left,
    rotate,
    opacity,
    fontFamily,
    fontSize,
    fontWeight,
    italic,
    color,
    textAlign,
    xFontSpacing,
    yFontSpacing,
    textDecoration
  } = val
  wrapStyles.value = {
    width: `${width * scale}px`,
    height: `${height * scale}px`,
    left: `${left * scale}px`,
    top: `${top * scale}px`,
    opacity: opacity,
    transform: `rotate(${rotate}deg)`,
    index: props.index + 1
  }
  imgWrapStyles.value = {
    width: `${width}px`,
    height: `${height}px`,
    transform: `scale(${scale})`
  }
  textWrapStyles.value = {
    width: `${width}px`,
    height: `${height}px`,
    fontFamily: `${fontFamily}, Arial`,
    fontSize: `${fontSize}px`,
    fontWeight: fontWeight ? 'bold' : 'normal',
    fontStyle: italic ? 'italic' : 'normal',
    color: `#${color}`,
    textAlign: textAlign,
    letterSpacing: `${xFontSpacing}px`,
    lineHeight: yFontSpacing,
    transform: `scale(${scale})`,
    textDecoration
  }
}, { immediate: true, deep: true })
watch(
  size.value,
  (val) => {
    setWrapStyles(val)
    imgWrapStyles.value.transform = `scale(${val / 100})`
    textWrapStyles.value.transform = `scale(${val / 100})`
  },
  { immediate: true }
)

// 挂载前
onBeforeMount(()=>{
  const chunk = props.chunk
  const scale = size.value / 100
  wrapStyles.value = {
    width: `${chunk.width * scale}px`,
    height: `${chunk.height * scale}px`,
    left: `${chunk.left * scale}px`,
    top: `${chunk.top * scale}px`,
    opacity: chunk.opacity,
    transform: `rotate(${chunk.rotate}deg)`,
    index: props.index + 1
  }
})
// 挂载后
onMounted(() => {
  if(props.isEdit) {
    console.log('is here onMounted--editorElRef', editorElRef.value)
    const currentChunkDom = editorElRef.value?.$el ? editorElRef.value?.$el : editorElRef.value
    let editTextEl = currentChunkDom.querySelector('.edit-content')
    console.log('editTextEl---', editTextEl)
    editTextEl.addEventListener('blur', editTextBlur)
    editTextEl.addEventListener('focus', editTextFocus)
    editTextEl.addEventListener('input', editTextChange)
  }
})
// 卸载前
onBeforeUnmount(async()=>{
  if(props.isEdit) {
    console.log('is here onBeforeUnmount')
    const currentChunkDom = editorElRef.value?.$el ? editorElRef.value?.$el : editorElRef.value
    let editTextEl = currentChunkDom.querySelector('.edit-content')
    await nextTick()
    editTextEl.removeEventListener('input', editTextChange)
    editTextEl.removeEventListener('focus', editTextFocus)
    editTextEl.removeEventListener('blur', editTextBlur)
  }
})

function setWrapStyles(size) {
  const chunk = props.chunk
  const scale = size / 100
  wrapStyles.value = {
    width: `${chunk.width * scale}px`,
    height: `${chunk.height * scale}px`,
    left: `${chunk.left * scale}px`,
    top: `${chunk.top * scale}px`,
    opacity: chunk.opacity,
    transform: `rotate(${chunk.rotate}deg)`,
    index: props.index + 1
  }
}
function editTextFocus() {
  console.log('is here editTextFocus--')
  // fouce的时候存下当前的index值，以防切换元素是index指向变了
  currentEditTextIndex.value = currentChunkIndex.value
}
function editTextBlur() {
  console.log('is here editTextBlur--')
  // let chunk = chunks.value[currentEditTextIndex.value]
  console.log('editorElRef--', editorElRef.value)
  const currentChunkDom = editorElRef.value?.$el ? editorElRef.value?.$el : editorElRef.value
  console.log('currentChunkDom--', currentChunkDom)
  let editTextEl = currentChunkDom.querySelector('.edit-content')
  let value = editTextEl.innerHTML
  chunks.value[currentEditTextIndex.value].textContent = value
  store.commit('poster/setStorageRecord')
}
function editTextChange(e) {
  console.log('is here editTextChange--')
  textChange(e)
}
const textChange = () => debounce((e) => {
  let target = e.target
  let width = target.offsetWidth
  let height = target.offsetHeight
  let chunk = chunks.value[currentChunkIndex.value]
  chunk.width = width
  chunk.height = height
  emit('textChange', width, height)
}, 200)
</script>

<style lang="scss">
.chunk-tb-popover {
  background: #303133;
  border-color: #303133;
  color: #fff;
  padding: 5px 8px;
  .popper__arrow {
    display: none;
  }
}
.editor-el {
  .chunk-disabled {
    cursor: not-allowed;
  }
}
</style>
